<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>co模块</title>
</head>
<body>
    <h1>co模块</h1>
    <h2>用于Generator函数的自动执行</h2>

    <script>
        // 简化版co模块实现
        function co(gen) {
            return new Promise((resolve, reject) => {
                const g = gen();
                
                function next(data) {
                    try {
                        const result = g.next(data);
                        if (result.done) {
                            resolve(result.value);
                        } else {
                            Promise.resolve(result.value).then(next, reject);
                        }
                    } catch (err) {
                        reject(err);
                    }
                }
                
                next();
            });
        }

        // 使用示例
        function* example() {
            try {
                const result1 = yield Promise.resolve(1);
                console.log(result1);
                const result2 = yield Promise.resolve(2);
                console.log(result2);
                return 'done';
            } catch (err) {
                console.error(err);
            }
        }

        co(example).then(value => {
            console.log('最终结果:', value);
        });

        // 处理并发操作
        function* parallel() {
            const [result1, result2] = yield [
                Promise.resolve(1),
                Promise.resolve(2)
            ];
            console.log('并发结果:', result1, result2);
        }

        co(parallel);

        // 实际应用示例
        function* loadUsers() {
            try {
                const response = yield fetch('https://api.example.com/users');
                const users = yield response.json();
                return users;
            } catch (err) {
                console.error('加载用户失败:', err);
            }
        }

        // co(loadUsers).then(users => {
        //     console.log('用户列表:', users);
        // });

        // 递归遍历
        function* iterTree(tree) {
            if (Array.isArray(tree)) {
                for(let i = 0; i < tree.length; i++) {
                    yield* iterTree(tree[i]);
                }
            } else {
                yield tree;
            }
        }

        const tree = ['a', ['b', 'c'], ['d', 'e']];
        co(function* () {
            for (let x of iterTree(tree)) {
                console.log(x);
            }
        });
    </script>
</body>
</html> 